package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传素材图片
     * @param multipartFile:
     * @return ResponseResult
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
       /* //1.检查参数
        if(multipartFile==null || multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.数据处理
        //2.1处理文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //2.2获取原始文件的后缀名  **.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //3.将图片上传到minIO
        try {
         String url= fileStorageService.uploadImgFile("",fileName+postfix,multipartFile.getInputStream());
            //4.封装素材实体对象，并存入数据库，wm_material
            WmMaterial wmMaterial=WmMaterial.builder()
                    .url(url)
                    .userId(WmThreadLocalUtils.getUser().getId())
                    .isCollection((short)0)
                    .type((short)0)
                    .createdTime(new Date()).build();
            log.info("上传图片到MinIO,OK");
            this.save(wmMaterial);
            //5.将wm_material返回给前端
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("上传文件失败");
        }

        return null;*/
        //1.检查参数
        if(multipartFile==null)throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        //2.数据处理
          //2.1 生成唯一文件名UUID
        String fileName = UUID.randomUUID().toString().replace("-", "");
          //2.2 获取原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        String pastName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.业务操作
        try {
            //3.1调用file保存到minIO
            String url=fileStorageService.uploadImgFile("",fileName+pastName,multipartFile.getInputStream());
            //3.2 封装WmMaterial保存到数据库
            WmMaterial wmMaterial=WmMaterial.builder()
                    .userId(WmThreadLocalUtil.getUser().getId())
                    .url(url)
                    .type((short)0)
                    .isCollection((short)0)
                    .createdTime(new Date()).build();
            save(wmMaterial);
            //4.返回结果
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数
        if(dto==null)throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        dto.checkParam();
        //2.组装分页查询条件构造器
        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper= Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
                .orderByDesc(WmMaterial::getCreatedTime);

        //是否收藏
        if(dto.getIsCollection() != null && dto.getIsCollection() == 1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        //3.查询数据
        this.page(page,wrapper);

        //4.封装分页查询结果
        PageResponseResult result=new PageResponseResult((int)page.getCurrent(),(int)page.getSize(),(int)page.getTotal());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        result.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());
        result.setData(page.getRecords());//封装数据

        return result;

    }

    /**
     * 删除素材
     * @param id :
     * @return ResponseResult
     */
    @Override
    public ResponseResult delete(Integer id) {
        //1.检查参数
        if(id==null)throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        //2.数据处理(逻辑判断)TODO
        //3.将图片从minIO中删除
           //3.1根据id去查询数据库图片全路径
        fileStorageService.delete(this.getById(id).getUrl());
        //3.删除数据
        this.removeById(id);

        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏素材
     * @param id :
     * @return ResponseResult
     */
    @Override
    public ResponseResult collect(Integer id) {
        WmMaterial wmMaterial=new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection((short)1);
        this.updateById(wmMaterial);
        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 取消收藏素材
     * @param id :
     * @return ResponseResult
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        WmMaterial wmMaterial=new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection((short)0);
        this.updateById(wmMaterial);
        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }


}
